<?php

namespace curd;

use PDO;

class Query
{

    public function __construct(private PDO $pdo, private string $database)
    {
    }

    /**
     * 所有表
     *
     * @return array
     */
    public function tables(): array
    {
        $sql = "SELECT TABLE_NAME as `table`, TABLE_COMMENT as `comment`, TABLE_ROWS as `rows`,ENGINE as `engine` FROM information_schema.TABLES WHERE TABLE_SCHEMA = :database ";
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindParam(':database', $this->database);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }


    /**
     * 数据表详情
     *
     * @return array
     */
    public function tablesInfo(): array
    {
        $tables = [];
        foreach ($this->tables() as $table) {
            $tables[$table['table']] = array_merge(
                $table,
                [
                    'pk'      => 'id',
                    'fields'  => [],
                ]
            );
        }
        if (count($tables)) {
            $tablesStr = array_reduce(array_keys($tables), fn($str, $table) => $str . ($str ? "," : '') . "'{$table}'", '');
            $sql = "SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = :database AND TABLE_NAME IN ({$tablesStr})";
            $stmt = $this->pdo->prepare($sql);
            $stmt->bindParam(':database', $this->database);
            $stmt->execute();
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($result as $item) {
                $isPK = strtolower($item['COLUMN_KEY']) === 'pri';
                $tables[$item['TABLE_NAME']]['fields'][] = [
                    'sort'    => count($tables[$item['TABLE_NAME']]['fields']) + 1,
                    'name'    => $item['COLUMN_NAME'],
                    'type'    => $item['COLUMN_TYPE'],
                    'notnull' => strtolower($item['IS_NULLABLE']) === 'no',
                    'default' => $item['COLUMN_DEFAULT'],
                    'primary' => $isPK,
                    'autoinc' => strtolower($item['EXTRA']) === 'auto_increment',
                    'comment' => $item['COLUMN_COMMENT'],
                ];
                if ($isPK) {
                    $tables[$item['TABLE_NAME']]['pk'] = $item['COLUMN_NAME'];
                }
            }
        }
        return $tables;
    }

}

